package com.nantian.nfcm.bms.report.web;

import com.nantian.nfcm.bms.loan.entity.LoanAssignReport;
import com.nantian.nfcm.bms.report.service.LoanAssignReportService;
import com.nantian.nfcm.bms.report.vo.LoanAssignReportBean;
import com.nantian.nfcm.util.DataUtil;
import com.nantian.nfcm.util.DateUtil;
import com.nantian.nfcm.util.ServiceException;
import com.nantian.nfcm.util.service.ParamService;
import com.nantian.nfcm.util.vo.GridData;
import com.nantian.nfcm.util.vo.LoginBean;
import com.nantian.nfcm.util.vo.ResultInfo;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping(("/reportAssign"))
public class LoanAssignReportController extends ReportController {
    private static Logger log = Logger.getLogger(LoanReportController.class.getName());
    private ParamService paramService;
    private LoanAssignReportService loanAssignReportService;
    private static final int limit = 500;
    private static final String fileSavePath = "fileSavePath";
    private String excelPath = "";//指定到服务器某个文件路径

    @Autowired
    public LoanAssignReportController(ParamService paramService, LoanAssignReportService loanAssignReportService) {
        this.paramService = paramService;
        this.loanAssignReportService = loanAssignReportService;
    }

    @RequestMapping("/loanAssignReport")
    @ResponseBody
    public ResultInfo poiLoanReport(LoanAssignReportBean loanAssignReportBean, HttpServletRequest request) {
        ResultInfo resultInfo = new ResultInfo();
        try {
            String savePath = paramService.findParamById(fileSavePath).getParamValue();
            if (savePath == null || savePath.equals("")) {
                throw new ServiceException("参数[" + fileSavePath + "]错误");
            }
            if(!new File(savePath).exists()){
                new File(savePath).mkdirs();
            }
            String time = DateUtil.getCurrentTime("yyyyMMddHHmmss");
            String fileName = "loanAssignReport" + time + ".xlsx";
            String path = savePath + File.separator + fileName;
            LoginBean loginBean = (LoginBean) request.getSession().getAttribute("loginInfo");
            String formatTime = DateUtil.getFormatTime(time);

            String title = "盘龙联社个人金融业务部回交贷款清单";
            String[] headerNames = {"贷款编号", "贷款上报日期", "贷款人姓名", "贷款人身份证", "贷款类型", "贷款金额（万元）",
                    "审查意见金额（万元）", "审查意见期限", "审查意见利率", "审查意见担保方式", "审查意见还款方式", "审查人",
                    "审查结果", "补件领取人", "资料接收"};
            String[] headerColumns = {"loanId","pickupTime","borrowerName", "credentialNo", "businessType",
                    "amount", "apprAmount", "apprTerm", "apprRate","apprGuaranteeMethod2", "apprRepaymentMethod",
                    "examineHandler","loanResult","NULL","NULL"};
            String operater = "【操作人员】：" + loginBean.getRealName() + " 【时间】 : " + formatTime;
            getExcelFile(path,title,operater,headerNames,headerColumns,loanAssignReportBean);
            resultInfo.setSuccess("true");
            resultInfo.setData(fileName);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return resultInfo;
    }

    /**
     * 通过数据库查询后导出excel报表
     *
     * @throws Exception
     */
    protected void getExcelFile(String filePath, String title, String operater,
                                String[] headerNames, String[] headerColumns,
                                LoanAssignReportBean loanAssignReportBean) {
        String sheetName = "exportData";
        int colCount = headerNames.length;
        Workbook workbook = null;
        Sheet sheet = null;
        FileOutputStream out = null;
        try {
            File file = new File(filePath);
            out = new FileOutputStream(file);
            workbook = new XSSFWorkbook();
            sheet = workbook.createSheet(sheetName);

            createTitle(workbook, sheet, title, 0, 0, 0, colCount);
            createOperater(workbook, sheet, operater, 1, 1, 0, colCount);
            createHeader(workbook, sheet, headerNames, 2, 1, 0);

            GridData<LoanAssignReport> gridData = loanAssignReportService.findByCondition(0, limit, loanAssignReportBean);
            List<LoanAssignReport> datas = gridData.getData();
            if (datas != null && datas.size() > 0) {
                int nextRow = wirteExcel(workbook, sheet, headerColumns, 3, 0, datas);
                loanAssignReportService.updateLoanAssignReport(datas);
                int totalPage = gridData.getTotalPage();
                for (int i = 1; i < totalPage; i++) {
                    gridData = loanAssignReportService.findByCondition(i, limit, loanAssignReportBean);
                    datas = gridData.getData();
                    loanAssignReportService.updateLoanAssignReport(datas);
                    nextRow = wirteExcel(workbook, sheet, headerColumns, nextRow, 0, datas);
                }
            } else {
                createNull(workbook, sheet, 3, 3, 0, colCount);
            }
            workbook.write(out);
        } catch (FileNotFoundException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        } catch (ServiceException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
    }

    @RequestMapping("/downloadExcel")
    // @ResponseBody
    public void downloadExcel(String fileName,HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        String path = "";
        String savePath = paramService.findParamById(fileSavePath).getParamValue();
        if(excelPath.equals(""))
        {
            path = savePath+File.separator+fileName;
        }
        else
        {
            path = excelPath + fileName;
        }
        File file = new File(path);
        downloadFile(file,request,response);

        DataUtil.deleteFileOrFolder(file);
    }

    /**
     * 查询贷款明细报表信息
     * @param loanAssignReportBean loanAssignReportBean
     * @param request request
     * @return ResultInfo ResultInfo
     */
    @RequestMapping("/findLoanAssignByCondition")
    @ResponseBody
    public ResultInfo findLoanInfosByCondition(HttpServletRequest request, int page, int size, LoanAssignReportBean loanAssignReportBean) {
        ResultInfo resultInfo = new ResultInfo();
        try {
            GridData<LoanAssignReport> gd = loanAssignReportService.findByCondition(page, size, loanAssignReportBean);
            resultInfo.setData(gd.getData());
            resultInfo.setNumber(gd.getNumber());
            resultInfo.setPage(gd.getPage());
            resultInfo.setTotalPage(gd.getTotalPage());
            resultInfo.setSuccess("true");
        } catch (Exception e) {
            log.error(e.getMessage());
            resultInfo.setSuccess("false");
            resultInfo.setData(e.getMessage());
        }
        return resultInfo;
    }
}
